package command.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Conversation;
import model.MessageCommunication;
import server.ClientThread;
import server.Server;

public class InviteUserToChatServer implements CommandServer {

    private String userInvites;
    private String conversationID;
    private boolean isInvitation = false;

    public InviteUserToChatServer() {
    }

    public void setIsInvitationAtTrue() {
        isInvitation = true;
    }

    public void setUserInvites(String userNickName) {
        userInvites = userNickName;
    }

    public void setConversationID(String idOfConversation) {
        conversationID = idOfConversation;
    }

    @Override
    public void execute(ClientThread clientThread) {
        ArrayList<String> userList;
        try {
            if (!isInvitation) {
                userList = (ArrayList<String>) clientThread.getObjectInputStream().readObject();
                MessageCommunication newMessage = (MessageCommunication) clientThread.getObjectInputStream().
                        readObject();
                Conversation conversation = (Conversation) clientThread.getObjectInputStream().readObject();
                conversationID = conversation.getConversationID();
                userInvites = newMessage.getMessage();
                Server.addConversation(conversation);
                Server.sendInvitationToConversation(userList, userInvites, conversationID);
            } else {
                clientThread.getObjectOutputStream().writeObject(
                        new MessageCommunication(true, "inviteusertochatclient"));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(new MessageCommunication(true, userInvites));
                clientThread.getObjectOutputStream().flush();
                clientThread.getObjectOutputStream().writeObject(new MessageCommunication(true, conversationID));
            }
        } catch (ClassNotFoundException | IOException ex) {
            Logger.getLogger(InviteUserToChatServer.class.getName()).log(Level.SEVERE,
                    "Fallo al invitar a un usuario a una conversación", ex);
        }
    }
}
